package com.yry.timertask.chapter33;

import org.junit.jupiter.api.Test;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class MyTimerDifferenceTest {

	@Test
	public void scheduleTest(){
		//1.规定时间格式
		Calendar calendar = Calendar.getInstance();
		final SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("Current exec time is:"+sf.format(calendar.getTime()));
//		 calendar.add(Calendar.SECOND,3);

		//设置成6S前的时间，若当前时间为2016-12-28 00:00:06
		calendar.add(Calendar.SECOND,-6);
		//设置之后的时间为2016-12-28 00:00:00
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				System.out.println("Scheduled exec time is:"+sf.format(scheduledExecutionTime())+", Task is being executed!");
			}
		}, calendar.getTime(), 2000);
		//休眠5s
		try {
			Thread.sleep(5000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void scheduleAtFixRateTest(){
		//1.规定时间格式
		Calendar calendar = Calendar.getInstance();
		final SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("Current exec time is:"+sf.format(calendar.getTime()));
//		 calendar.add(Calendar.SECOND,3);

		//设置成6S前的时间，若当前时间为2016-12-28 00:00:06
		calendar.add(Calendar.SECOND,-6);
		//设置之后的时间为2016-12-28 00:00:00
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				System.out.println("Scheduled exec time is:"+sf.format(scheduledExecutionTime())+ ", Task is being executed!");
			}
		}, calendar.getTime(), 2000);

		//休眠5s
		try {
			Thread.sleep(5000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}


}
